
//
//  CSaddPerCardViewController.m
//  ZSYH
//
//  Created by 主事丫环 on 2019/4/17.
//  Copyright © 2019 魏堰青. All rights reserved.
//

#import "CSaddPerCardViewController.h"
#import "JYBDBankCardVC.h"
#import "MBProgressHUD.h"
#import "JYBDIDCardVC.h"
#import "DISBBuildingViewController.h"
#import "TabBarViewController.h"
#import <AipOcrSdk/AipOcrSdk.h>
#import "BBuildingShopViewController.h"

@interface CSaddPerCardViewController ()
{
    // 默认的识别成功的回调
    void (^_successHandler)(id);
    // 默认的识别失败的回调
    void (^_failHandler)(NSError *);
}
@property (weak, nonatomic) IBOutlet UIImageView *upImage;
@property (weak, nonatomic) IBOutlet UIImageView *dowImage;
@property (weak, nonatomic) IBOutlet UIButton *upBut;
@property (weak, nonatomic) IBOutlet UIButton *dowBUt;
@property(nonatomic,strong)NSString *cardstr;
@property(nonatomic,strong)NSString *cardname;

@end

@implementation CSaddPerCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"身份证";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    
    self.dowBUt.hidden = YES;
    
    //授权方法1：在此处填写App的Api Key/Secret Key
    [[AipOcrService shardService] authWithAK:@"ms8H0dPSnKFmQs4nppHNSlrZ" andSK:@"3wKG7naZHvqzhAHeMRvTwZgT0REHxzCI"];
    
    [self configCallback];
}

- (void)configCallback {
    __weak typeof(self) weakSelf = self;
    
    // 这是默认的识别成功的回调
    _successHandler = ^(id result){
        NSLog(@"%@", result);
        NSString *title = @"识别结果";
        NSMutableString *message = [NSMutableString string];
        
        if(result[@"words_result"]){
            if([result[@"words_result"] isKindOfClass:[NSDictionary class]]){
                [result[@"words_result"] enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                    if([obj isKindOfClass:[NSDictionary class]] && [obj objectForKey:@"words"]){
                        [message appendFormat:@"%@: %@\n", key, obj[@"words"]];
                    } else {
                        [message appendFormat:@"%@: %@\n", key, obj];
                    }
                }];
            } else if([result[@"words_result"] isKindOfClass:[NSArray class]]){
                for(NSDictionary *obj in result[@"words_result"]){
                    if([obj isKindOfClass:[NSDictionary class]] && [obj objectForKey:@"words"]){
                        [message appendFormat:@"%@\n", obj[@"words"]];
                    } else {
                        [message appendFormat:@"%@\n", obj];
                    }
                }
            }
        } else {
            [message appendFormat:@"%@", result];
        }
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:weakSelf cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertView show];
        }];
    };
    
    _failHandler = ^(NSError *error){
        NSLog(@"%@", error);
        NSString *msg = [NSString stringWithFormat:@"%li:%@", (long)[error code], [error localizedDescription]];
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [[[UIAlertView alloc] initWithTitle:@"识别失败" message:msg delegate:weakSelf cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
        }];
    };
}

- (IBAction)upAction:(UIButton *)sender {
    
    kWeakSelf;
    UIViewController * vc =
    [AipCaptureCardVC ViewControllerWithCardType:CardTypeLocalIdCardFont
                                 andImageHandler:^(UIImage *image) {
        
        [[AipOcrService shardService] detectIdCardFrontFromImage:image
                                                     withOptions:nil
                                                  successHandler:^(id result){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                weakSelf.upImage.image = image;
                weakSelf.cardstr = result[@"words_result"][@"公民身份号码"][@"words"];
                weakSelf.cardname = result[@"words_result"][@"姓名"][@"words"];
                weakSelf.upBut.hidden = YES;
                weakSelf.dowBUt.hidden = NO;
                
                [weakSelf dismissViewControllerAnimated:YES completion:^{}];
            });
        }
            failHandler:_failHandler];
    }];
    [self presentViewController:vc animated:YES completion:nil];
    
    //    kWeakSelf;
    //    JYBDIDCardVC *AVCaptureVC = [[JYBDIDCardVC alloc] init];
    //
    //    AVCaptureVC.finish = ^(JYBDCardIDInfo *info, UIImage *image)
    //    {
    //        if(strIsEmpty(info.name)) {
    //            ShowToastWithText(@"请拍摄身份证正面照");
    //        } else {
    //            self.upImage.image = image;
    //            self.cardstr = info.num;
    //            self.cardname = info.name;
    //            self.upBut.hidden = YES;
    //            self.dowBUt.hidden = NO;
    //        }
    //    };
    //    [self.navigationController pushViewController:AVCaptureVC animated:YES];
}

- (IBAction)dowAction:(UIButton *)sender {

    kWeakSelf;
    UIViewController * vc =
    [AipCaptureCardVC ViewControllerWithCardType:CardTypeLocalIdCardBack
                                 andImageHandler:^(UIImage *image) {
        
        [[AipOcrService shardService] detectIdCardFrontFromImage:image
                                                     withOptions:nil
                                                  successHandler:^(id result){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.dowImage.image = image;
                weakSelf.dowBUt.hidden = YES;
                [weakSelf dismissViewControllerAnimated:YES completion:^{}];
            });
        }
                                                     failHandler:_failHandler];
    }];
    [self presentViewController:vc animated:YES completion:nil];
    
    //    JYBDIDCardVC *AVCaptureVC = [[JYBDIDCardVC alloc] init];
    //
    //    AVCaptureVC.finish = ^(JYBDCardIDInfo *info, UIImage *image)
    //    {
    //        if(strIsEmpty(info.name)) {
    //            self.dowImage.image = image;
    //            self.dowBUt.hidden = YES;
    //        }else{
    //            ShowToastWithText(@"请拍摄身份证反面照");
    //        }
    //    };
    //    [self.navigationController pushViewController:AVCaptureVC animated:YES];
}

- (IBAction)baocunAction:(UIButton *)sender {
    if (!_upBut.hidden) {
        ShowToastWithText(@"请拍摄身份证正面照");
        return;
    }
    if (!_dowBUt.hidden) {
        ShowToastWithText(@"请拍摄身份证反面照");
        return;
    }
    NSMutableArray *muarr = [NSMutableArray arrayWithCapacity:1];
    [muarr addObject:_upImage];
    [muarr addObject:_dowImage];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    param[@"id_card"] = _cardstr;
    param[@"name"] = _cardname;
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    kWeakSelf;
    
    [NetWorkTool UploadPicWithUrl:upphoneIdracd param:param key:@"image" image:muarr withSuccess:^(id dic) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        ShowToastWithText(@"上传成功");
        //        if (weakSelf.mybliock) {
        //            weakSelf.mybliock(weakSelf.cardstr);
        //        }
        
        if ([self.iscenter isEqualToString:@"center"]) {
            [self.navigationController popViewControllerAnimated:YES];
            return ;
        }
        
        NSString *sss =[USER_DEFAULT objectForKey:@"level"];
        
        if ([weakSelf.iscenter isEqualToString:@"center"]) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
            return;
        }
        
        if ([sss isEqualToString:@"1"]) {
            //去展示
            TabBarViewController *tabbar = [[TabBarViewController alloc]init];
            [UIApplication sharedApplication].keyWindow.rootViewController = tabbar;
        } else {
            if (strIsEmpty(weakSelf.isstr)) {
                //绑定
                //[self.navigationController popToViewController:[DISBBuildingViewController new] animated:YES];
                [self.navigationController pushViewController:[BBuildingShopViewController new] animated:YES];
            } else {
                if ([sss isEqualToString:@"2"]) {
                    //去展示b有收益
                    TabBarViewController *tabbar = [[TabBarViewController alloc]init];
                    [UIApplication sharedApplication].keyWindow.rootViewController = tabbar;
                } else {
                    //去展示b没收益
                    TabBarViewController *tabbar = [[TabBarViewController alloc]init];
                    [UIApplication sharedApplication].keyWindow.rootViewController = tabbar;
                }
            }
        }
        //[self.navigationController  popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        
    }];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
